<?php
namespace app\api\controller\v1;
use think\admin\Controller;
use think\Response;
use app\data\model\DataDevice;
use app\data\model\DataDeviceLog;
use app\data\model\DataDeviceCatGroup;
use app\data\model\DataWarningLog;
use app\data\model\DataCat;
use app\data\model\DataCatLog;
use app\data\service\DeviceService;
use app\data\service\IotThingService;

use AlibabaCloud\SDK\Iot\V20180120\Models\BatchUpdateDeviceNicknameRequest\deviceNicknameInfo;
/**
 * 设备数据接口
 * @class Device
 * @package app\api\controller\v1
 *
 */
class Device extends Controller
{
    public function update_nickname(){
        $nickname = input('post.nickname');//设备iotId
        $iotId= input('param.id');
        $data=[
            "nickname" => $nickname,
            "iotId" => $iotId
        ];
        $mod = new DeviceService();
        $response = $mod->BatchUpdateDeviceNickname($data);
        if($response['err_code'] == 1){
            $this->error($response['data']);
        }else{
            $res = $response['data'];
            if($res->body->code !=''){
                $this->error($res->body->errorMessage);
            }else{
                DataDevice::mk()->where(['iotId'=>$iotId])->update(['nickname'=>$nickname]);
                $this->success('修改成功');
            }
        }
    }
    public function get_base_info(){
        $id = input('get.id');//设备iotId
        $res = DataDevice::mk()->where(['iotId'=>$id])->find();
        $this->success('success',$res);
    }
    public function set_protect_weight(){
        $id = input('post.id');//设备iotId
        $v = input('post.v');
        DataDevice::mk()->where(['iotId'=>$id])->update(['weight_pro'=>$v]);
        $this->success('success');
    }
    //获取设备物模型属性快照
    public function get_settings(){
        $id = input('get.id');//设备iotId
        $service_dev = new DeviceService();
        $res = $service_dev->getDevicePro($id);
        $res['dev_info'] =  DataDevice::mk()->where(['iotId'=>$id])->find();
        $this->success('success',$res);
    }
    //绑定未知宠物并更新体重
    public function select_unknown(){
        $params = input('post.');
        //如厕日志数据
        $cat_log = DataDeviceLog::mk()->where(['id'=>$params['id']])->find();
        $cat_log_id = $cat_log['log_id'];//如厕日志ID
        $data=[
            'type'=>2,
            'cat_id'=>$params['cat_id']
        ];
        DataDeviceLog::mk()->where(['id'=>$params['id']])->update($data);//更新设备日志
        DataCatLog::mk()->where(['id'=>$cat_log_id])->update(['cat_id'=>$params['cat_id']]);//更新如厕日志
        //检查当前日志 如果之后有新数据跳过，没有则更新体重
        $check_last_time = DataDeviceLog::mk()
            ->where(['cat_id'=>$params['cat_id']])
            ->whereTime('create_at', '>',$cat_log['create_at'])->count();
        if($check_last_time == 0){
            $weight =  DataCatLog::mk()->where(['id'=>$cat_log_id])->value('weight');
            DataCat::mk()->updateWeight($params['cat_id'],$weight);
        }
        $this->success('获取成功',$data);
    }
    //获取设备基础信息
    public function get_property(){
        $id = input('get.id');//设备iotId
        $device = DataDevice::mk()->where(['iotId'=>$id])->find();
        if(!empty($device)){
            $service_dev = new DeviceService();
            $device['prop'] = $service_dev->getDevicePro($id);
            $device['clean'] = $service_dev->CleanTimes($id);
            $device['toilet'] = $service_dev->toiletTimes($id);
            $map[]=['c.member_id','=',$this->request->uid];
            $device['cats'] =  DataCat::mk()->getList($map,20);
            $notice_count =  DataWarningLog::mk()->alias('l')->join('data_device d','d.iotId = l.iot_id ')
                ->where(['d.member_id'=>$this->request->uid,'is_read'=>0])->count();
            $device['notice_count'] = $notice_count;
            $this->success('获取成功',$device);
        }else{
            $this->success('获取失败',[]);
        }
    }
    //今日设备日志
     function get_today_work_log(){
         $id = input('param.id');
         $res = DataDeviceLog::mk()->alias('l')->field('l.*,c.nickname,c.avatar,date_format(l.create_at, "%m-%d") as day,date_format(l.create_at, "%H:%i") as time')
            ->leftjoin('data_cat c','c.id = l.cat_id')
            ->where(['l.iot_id'=>$id,'group_id'=>0])->order('l.id desc')
            ->paginate(10,200)->toArray();
          //重组数据
          $group_ids = array_column($res['data'], 'id');
          $sonInfo = DataDeviceLog::mk()->alias('l')
              ->field('l.*,date_format(l.create_at, "%m-%d") as day,date_format(l.create_at, "%H:%i") as time')
              ->where('group_id','in',$group_ids)
              ->where(['l.iot_id'=>$id])->order('l.id asc')->select()->toArray();
         foreach($res['data'] as &$v){
             $son= array_filter($sonInfo, function($item) use ($v) {
                 return $item['group_id'] == $v['id'];
             });

             $v['son'] = array_values($son);
         }
          $this->success('获取成功',$res);
    }
    //当前用户绑定的设备
    public function my()
    {
        $res = DataDevice::mk()->my($this->request->uid);
        $this->success('success',$res);
    }
    //解除设备绑定
    public function del()
    {
        $id = input('param.id');
        $res = DataDevice::mk()->where(['member_id'=>$this->request->uid,'iotId'=>$id])->update(['member_id'=>0]);//解绑设备
        DataDeviceCatGroup::mk()->where(['member_id'=>$this->request->uid,'iotId'=>$id])->deleted();//删除分组
        $this->success('success',$res);
    }
    //绑定设备
    public function bind()
    {

        $json = input('param.json');
        log_result($json);
        $json_arr = json_decode($json,true);
        $json_str = join("",$json_arr);
        log_result('json_str:'.$json_str);
        log_result($this->request->uid);
        $arr = explode(',',$json_str);
        $new_arr = [];
        foreach($arr as $v){
            $arr_a = explode(':',$v);
            $new_arr[$arr_a[0]]=$arr_a[1];
        }
        log_result(json_encode($new_arr));
        $new_arr = json_decode(json_encode($new_arr),true);
        log_result($new_arr['ProductKey']);
        log_result($new_arr['DeviceName']);
        $uid = DataDevice::mk()->where(['productKey'=>$new_arr['ProductKey'],'deviceName'=>$new_arr['DeviceName'],'is_deleted'=>0])->value('member_id');
        if($uid>0){
            $this->success('success',['is_bind'=>1]);
        }else{
            DataDevice::mk()->where(['productKey'=>$new_arr['ProductKey'],'deviceName'=>$new_arr['DeviceName']])->update(['member_id'=>$this->request->uid,'nickname'=>'智能猫砂盆']);
            $this->success('success',['is_bind'=>0]);
        }

    }
    //设置物模型属性
    public function set_pro(){
        $class = new IotThingService();
        $iotId=input('post.id');
        $title = input('post.title');
        $value = input('post.v');
        $item = '{"'.$title.'":'.$value.'}';
        //$this->error($item);
        $res = $class->setProp($iotId,$item);
        if($res['err_code'] == 0){
            $response = $res['data'];
            if($response->body->code !=''){
                $this->error($response->body->code);
            }else{
//                if($title == 'Light'){
//                    $value_arr = json_decode($value,true);
//                    $key = key($value_arr);
//                    if ($key == 'Mode'){
//                        $arr = [
//                            '1'=>'科技蓝',
//                            '2'=>'科技粉',
//                            '3'=>'科技白',
//                            '4'=>'薄荷绿',
//                            '5'=>'紫罗兰',
//                            '6'=>'清新黄',
//                            '7'=>'毒液绿',
//                            '8'=>'粉紫色',
//                            '9'=>'冰湖蓝',
//                            '10'=>'自定义颜色',
//                        ];
//                        $remark =  '灯光切换为'.($arr[$value_arr['Mode']]);
//                        $log_data=[
//                            'iot_id'=>$iotId,
//                            'remark'=>$remark
//                        ];
//                        DataDeviceLog::mk()->insert($log_data);
//                    }
//
//                }
                $this->success('success',json_decode($response->body->data->messageId,true));
            }
        }else{
            $this->error($res['data']);
        }
    }
    //通知设备物模型执行服务
    public function handle()
    {
        $iot_id = input('post.id');
        $type = input('post.type');
        $title='';
        $remark='';
        $args='{}';
        if($type == '0'){
            $title = 'Clean_Hand';//手动清理
            $args='{"state":0}';
            $remark = '手动清理开始';
        }else if($type == 1){
            $title = 'Add_CatLitter'; //添加猫砂
            $remark = '添加猫砂';
        }else if($type == 2){
            $title = 'Sterilization'; //深度杀菌
            $remark = '手动杀菌开始';
            $args='{"state":0}';
        }else if($type == 3){
            $title = 'Push_Bin'; //弹出集便舱
            $remark = '弹出集便舱';
        }else if($type == 4){
            $title = 'Calibrate_Litter'; //倒沙矫正
            $args='{"state":0}';
            $remark = '倒沙矫正';
        }else if($type == 5){
            $title = 'Smooth'; //一键抚平
            $remark = '一键抚平开始';
            $args='{"state":0}';
        }else if($type == 6){
            $title = 'Power'; //开机
            $remark = '开机';
            $args='{"state":0}';
        }else if($type == 7){
            $title = 'Power'; //
            $remark = '待机';
            $args='{"state":1}';
        }else if($type == 8){
            $title = 'Motor_Reset'; //
            $remark = '自检及复位';
        }else if($type == 'pause'){
            $state = input('post.state');
            if($state == 1 || $state == 2){
                //抚平暂停
                $title ="Smooth";
                $remark = $state == 1?'开门抚平暂停':'暂停关门抚平暂停';
                $args='{"state":1}';
            }
            if($state == 3 || $state == 4 || $state==5){
                //清理
                if($state == 3){
                    $remark = '自动清理暂停';
                }elseif($state == 4){
                    $remark = '定时清理暂停';
                }elseif($state == 5){
                    $remark = '手动清理暂停';
                }
                $title ="Clean_Hand";
                $args='{"state":1}';
            }
            if($state == 7){
                //抚平暂停
                $title ="Calibrate_Litter";
                $remark = '暂停猫砂量矫正及倒砂';
                $args='{"state":1}';
            }
        }else if($type == 'continue'){
            $state = input('post.state');
            if($state == 10 || $state == 11){
                $title ="Smooth";
                $remark = $state == 11?'开门抚平继续':'关门抚平继续';
                $args='{"state":2}';
            }
            if($state == 12 || $state == 13 || $state==14){
                //清理
                if($state == 12){
                    $remark = '自动清理继续';
                }elseif($state == 13){
                    $remark = '定时清理继续';
                }elseif($state == 14){
                    $remark = '手动清理继续';
                }
                $title ="Clean_Hand";
                $args='{"state":2}';
            }
            if($state == 15){
                //抚平暂停
                $title ="Calibrate_Litter";
                $remark = '猫砂量矫正及倒砂继续';
                $args='{"state":2}';
            }

        }else if($type == 'stop'){
            //停止杀菌
            $remark='手动杀菌停止';
            $title ="Sterilization";
            $args='{"state":3}';
        }
        $class = new IotThingService();
        $res = $class->setService($iot_id,$title,$args);
        if($res['err_code'] == 0){
            $response = $res['data'];
            if($response->body->code !=''){
                $this->success('error',$response->body->code);
            }else{
              //  $this->insert_log($iot_id,$remark);//操作日志
                $data = json_decode($response->body->data->result,true);
                $this->success('success',$data);
            }
        }else{
            $this->success('error',$res['data']);
        }
    }

    function  insert_log($iotId,$remark){
        //添加到设备日志
        $log_data=[
            'iot_id'=>$iotId,
            'type'=>1,
            'cat_id'=>0,
            'duration'=>0,//单位秒
            'cat_weight'=>0,//单位克
            'remark'=>$remark
        ];
        DataDeviceLog::mk()->insert($log_data);
    }
}
